package com.i2863.watchdog;

import com.i2863.watchdog.util.DateUtil;
import com.i2863.watchdog.util.HttpUtil;
import com.i2863.watchdog.util.ResponseInfo;
import com.i2863.watchdog.wangsu.MatocloudSmsUtil;
import com.i2863.watchdog.yunpian.SmsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xuweiwei
 * @date 2017/12/6
 */
public class WatchDog {
    private static final Logger logger = LoggerFactory.getLogger(WatchDog.class);
    public static final String FORMAT = "yyyy-MM-dd HH:mm:ss";
    private List<InspectTask> taskList;
    private Map<String, Date> mailMap = new ConcurrentHashMap<>();


    public boolean pass(InspectTask task) {
        try {
            ResponseInfo responseInfo = HttpUtil.get(task.getUrl());
            return task.getInspector().pass(responseInfo);
        } catch (IOException e) {
            logger.error("请求发生异常", e);
            return false;
        }
    }


    public void report(InspectTask task) {
        Date now = new Date();
        Date lastErrorDate = mailMap.get(task.getName());
        if (lastErrorDate != null) {
            int hours = (int) ((now.getTime() - lastErrorDate.getTime()) / 1000 / 3600);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            //白天1小时通知1次
            if (hour >= 8 && hours < 1) {
                return;
            }
            //晚上4小时通知1次
            if (hour < 8 && hours < 4) {
                return;
            }
        }
        String date = DateUtil.format(now, FORMAT);
        String msg = MatocloudSmsUtil.PREFIX + task.getName() + "系统出现故障,时间:" + date + ".请尽快处理";
        //发邮件
        for (Contact contact : task.getContactGroup().getContactList()) {
            try {
                String tel = contact.getTel();
                SmsUtil.sendMsg(tel, msg);
                logger.info("发送短信成功");
            } catch (Exception e) {
                logger.error("发送短信失败", e);
            }
        }

        //更新最后一次发短信的时间
        mailMap.put(task.getName(), now);
    }

    public boolean pass3(InspectTask task) {
        for (int i = 0; i < 3; i++) {
            boolean result = pass(task);
            if (result) {
                return true;
            }
        }
        return false;
    }


    @Scheduled(cron = "0 */5 * * * ?")
    public void run() {
        logger.info("开门狗开始运行");
        for (InspectTask task : taskList) {
            boolean pass = pass3(task);
            if (!pass) {
                report(task);
            }
        }
    }


    public List<InspectTask> getTaskList() {
        return taskList;
    }

    public void setTaskList(List<InspectTask> taskList) {
        this.taskList = taskList;
    }

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring_api_basic.xml");
        context.start();
    }

}
